#ifndef VNCCLIENT_H
#define VNCCLIENT_H

#include "protocol.h"
#include <QImage>
#include <QPoint>
#include <Qt>
#include <QTcpSocket>
#include <QTimer>
#include <QVariantMap>
#include "framebuffer.h"

class VncClient : public Protocol
{
    Q_OBJECT

public:
    explicit VncClient(QObject *parent = nullptr);
    ~VncClient();

    // 实现协议接口
    bool connectToHost(const QString &host, int port, const QString &password) override;
    void disconnectFromHost() override;
    QImage getDesktopImage() const override;
    void sendMouseEvent(const QPoint &pos, Qt::MouseButton button, bool pressed) override;
    void sendKeyEvent(int key, bool pressed) override;
    void sendText(const QString &text) override;
    void requestFrame(const QRect &region) override;
    void requestFullFrame() override;
    QStringList supportedFeatures() const override;
    bool hasFeature(const QString &feature) const override;
    void setConfiguration(const QVariantMap &config) override;
    QVariantMap getConfiguration() const override;
    int getFramerate() const override;
    void setFramerate(int fps) override;
    QSize getRemoteDesktopSize() const override;

private slots:
    void onConnected();
    void onDisconnected();
    void onError(QAbstractSocket::SocketError socketError);
    void onReadyRead();
    void updateFrame();

private:
    QTcpSocket *socket;
    QTimer *updateTimer;
    
    // VNC协议相关
    QString securityType;
    int majorVersion;
    int minorVersion;
    
    // 桌面信息
    int framebufferWidth;
    int framebufferHeight;
    FrameBuffer *frameBuffer;
    
    // 配置参数
    QVariantMap configuration;
    int targetFps;
    
    // 初始化连接
    void initializeConnection();
    void handleHandshake();
    void handleSecurity();
    void handleInitialization();
    
    // 发送和接收数据
    void sendData(const QByteArray &data);
    QByteArray receiveData(int size);
    
    // 处理VNC消息
    void processMessages();
    void handleFramebufferUpdate();
    void handleBell();
    void handleClipboardUpdate();
};

#endif // VNCCLIENT_H